<template>
  <div class="page-container">
    <div class="card">
      <el-input class="card-input" clearable @clear="load" v-model="data.findparams.username" placeholder="请输入账号查询"
        :prefix-icon="Search" @keyup.enter="load"></el-input>
      <el-input class="card-input" clearable @clear="load" v-model="data.findparams.nickname" placeholder="请输入名称查询"
        :prefix-icon="Search" @keyup.enter="load"></el-input>
      <el-button class="card-button" type="primary" @click="load">查 询</el-button>
      <el-button class="card-button" @click="reset">重 置</el-button>
    </div>
    <div class="card">
      <el-button class="card-button" type="primary" @click="handleAdd">新 增</el-button>
      <el-button class="card-button" type="danger" @click="deleteBatch">批量删除</el-button>
      <el-upload class="card-button" :action="data.importUrl" :headers="data.header" :show-file-list="false"
        :on-success="handleImportSuccess">
        <el-button type="success">批量导入</el-button>
      </el-upload>
      <el-button class="card-button" type="info" @click="exportSelect">批量导出已选</el-button>
      <el-button class="card-button" type="info" @click="exportAll">批量导出所有</el-button>
    </div>
    <div class="card">
      <el-table :data="data.tableData" style="width: 100%;"
        :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff', alignItems: 'center' }"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="头像" width="80">
          <template #default="scope">
            <el-image v-if="scope.row.avatar" :src="scope.row.avatar" class="myAvatar"
              :preview-src-list="[scope.row.avatar]" :preview-teleported="true" />
            <img v-else class="myAvatar" :src="getConfig('DEFAULT_USER_LOGO')" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="username" label="账号" />
        <el-table-column prop="nickname" label="名称" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button style="margin-right: 10px;" type="primary" icon="Edit" circle
              @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card">
      <el-pagination v-model:current-page="data.paginationData.pageNum" v-model:page-size="data.paginationData.pageSize"
        :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper"
        :total="data.paginationData.total" @change="load" />
    </div>
    <el-dialog v-model="data.addDialogparams.dialogVisible" title="管理员信息" width="40%" destroy-on-close>
      <el-form ref="addFormRef" :rules="data.addDialogparams.formRules" :model="data.addDialogparams.form"
        label-width="80" style="padding: 20px 30px 10px 0;">
        <el-form-item prop="username" label="账号">
          <el-input v-model="data.addDialogparams.form.username" autocomplete="off" placeholder="请输入账号"
            :disabled="data.addDialogparams.form.id != null" />
        </el-form-item>
        <el-form-item prop="nickname" label="名称">
          <el-input v-model="data.addDialogparams.form.nickname" autocomplete="off" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item prop="phone" label="电话">
          <el-input v-model="data.addDialogparams.form.phone" autocomplete="off" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="data.addDialogparams.form.email" autocomplete="off" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item prop="avatar" label="头像">
          <el-upload :action="getConfig('API_BASE_URL').replace(/\/?$/, '/') + 'files/upload'"
            :on-success="handleFileSuccess" :headers="data.Header" show-file-list="false" list-type="picture"
            :before-upload="beforeUpload">
            <el-image v-if="data.addDialogparams.logoUrl" :src="data.addDialogparams.logoUrl" class="myAvatar" />
            <el-button v-else type="primary">点击上传头像</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.addDialogparams.dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { Search } from '@element-plus/icons-vue';
import { reactive, ref } from 'vue';
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getConfig } from '@/utils/config';
import { useTokenStore } from '@/store/token';
import { useUserStore } from '@/store/user';
import {
  adminListPageService,
  adminAddService,
  adminUpdateService,
  adminDeleteService,
  adminDeleteBatchService
} from '@/api/user';
import { beforeUpload } from '@/utils/function';

const userStore = useUserStore()
const tokenStore = useTokenStore()
const data = reactive({
  importUrl: getConfig("API_BASE_URL") + '/admin/import',
  header: {
    token: tokenStore.token
  },
  addDialogparams: {
    logoUrl: '',
    dialogVisible: false,
    form: {
      username: '',
      nickname: '',
      phone: '',
      email: '',
    },
    formRules: {
      username: [
        { required: true, message: '请填写账号', trigger: 'blur' },
        { min: 3, message: '账号最少3位字符', trigger: 'blur' },
      ],
      nickname: [
        { required: true, message: '请填写名称', trigger: 'blur' },
      ],
      phone: [
        { required: true, message: '请填写电话', trigger: 'blur' },
      ],
      email: [
        { required: true, message: '请填写邮箱', trigger: 'blur' },
      ]
    }
  },
  findparams: {
    nickname: null,
    username: null,
  },
  tableData: [],
  paginationData: {
    pageNum: 1,
    pageSize: 5,
    total: 6
  },
  multipleSelectionvalue: []
})

const addFormRef = ref()

const load = async () => {
  const param = {
    pageNum: data.paginationData.pageNum,
    pageSize: data.paginationData.pageSize,
    nickname: data.findparams.nickname,
    username: data.findparams.username,
  }
  const result = await adminListPageService(param)
  data.tableData = result.list;
  data.paginationData.total = result.total;
}
load()

const reset = () => {
  data.findparams.nickname = null
  data.findparams.username = null
  load()
}

const handleAdd = () => {
  data.addDialogparams.dialogVisible = true
  data.addDialogparams.form = {}
}

const add = () => {
  // addFormRef是表单的引用
  addFormRef.value.validate(async (valid) => {
    if (valid) { //说明是表单验证通过的情况下
      await adminAddService(data.addDialogparams.form)
      data.addDialogparams.dialogVisible = false
      ElMessage.success("新增成功")
      load()
    }
  })
}

const handleEdit = (row) => {
  // data.addDialogparams.form = row  // 这样会浅拷贝
  data.addDialogparams.form = JSON.parse(JSON.stringify(row))  // 这样才会深度拷贝
  data.addDialogparams.logoUrl = data.addDialogparams.form.avatar
  data.addDialogparams.dialogVisible = true
}

const update = () => {
  // addFormRef是表单的引用
  addFormRef.value.validate(async (valid) => {
    if (valid) { //说明是表单验证通过的情况下
      await adminUpdateService(data.addDialogparams.form)
      data.addDialogparams.dialogVisible = false
      ElMessage.success("修改成功")
      load()
    }
  })

}

const save = () => {
  data.addDialogparams.form.id ? update() : add()
}

const del = (id) => {
  ElMessageBox.confirm(
    '删除后无法恢复，您确认删除所选数据吗?',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async res => {
    await adminDeleteService(id)
    ElMessage.success("删除成功")
    load()
  })
}

const handleSelectionChange = (rows) => {   //  rows是实际选择的数组
  data.multipleSelectionvalue = rows
}

const deleteBatch = () => {
  if (data.multipleSelectionvalue.length === 0) {
    ElMessage.warning('请选择需要删除的数据')
    return
  }
  ElMessageBox.confirm(
    '删除后无法恢复，您确认删除所选数据吗?',
    '删除确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async res => {
    let ids = []
    data.multipleSelectionvalue.map(item => {
      ids.push(item.id)
    })
    await adminDeleteBatchService(ids)
    ElMessage.success("批量删除成功")
    load()
  })
}

const exportSelect = () => {
  if (data.multipleSelectionvalue.length === 0) {
    ElMessage.warning('请选择需要导出的数据')
    return
  }
  exportAdmin(data.multipleSelectionvalue)
}

const exportAll = () => {
  exportAdmin()
}

const exportAdmin = (data) => {
  request.post(getConfig("API_BASE_URL") + '/admin/export', data, { responseType: 'blob' }).then(response => {
    const blobData = response.data;
    if (!(blobData instanceof Blob)) {
      return parseErrorBlob(blobData);
    }

    const fileName = parseFilename(
      response.headers['content-disposition'],
      '管理员信息.xlsx'
    );

    downloadFile(blobData, fileName);
    ElMessage.success("批量导出成功");
  })
}

const parseFilename = (contentDisposition, defaultName) => {
  if (!contentDisposition) return defaultName;

  const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
  const matches = filenameRegex.exec(contentDisposition);

  if (matches && matches[1]) {
    return matches[1].replace(/['"]/g, '');
  }

  return defaultName;
};

const downloadFile = (blob, fileName) => {
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');

  link.href = url;
  link.setAttribute('download', fileName);
  link.style.display = 'none';

  document.body.appendChild(link);
  link.click();

  // 延迟清理避免下载中断
  setTimeout(() => {
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }, 100);
};
function parseErrorBlob(blob) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = () => {
      try {
        const errorData = JSON.parse(reader.result);
        resolve(errorData.message || '服务器返回了未定义错误');
      } catch {
        resolve('无效的错误响应格式');
      }
    };
    reader.readAsText(blob);
  });
}


const handleImportSuccess = (res) => {
  if (res.code === '200') {
    ElMessage.success("批量导入成功")
    load()
  } else {
    ElMessage({
      showClose: true,
      message: res.msg,
      type: 'warning',
      duration: 0,
    })
  }
}

const handleFileSuccess = (res) => {
  if (res.code === '200') {
    ElMessage.success("头像上传成功")
    data.addDialogparams.form.avatar = res.data
  } else {
    ElMessage({
      showClose: true,
      message: res.msg,
      type: 'warning',
      duration: 0,
    })
  }
}
</script>